package com.jiangnan.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.CompoundButton
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.ActivityLoginBinding
import com.jiangnan.util.CurrentHolder
import com.jiangnan.util.CurrentLoginInfo
import com.jiangnan.util.NavigationUtil
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.AuthViewModel

class LoginActivity : BaseActivity(), View.OnClickListener, TextWatcher,
    CompoundButton.OnCheckedChangeListener {

    private lateinit var binding: ActivityLoginBinding
    private lateinit var viewModel: AuthViewModel
    val KEY_IS_LOGIN: String = "isLogin"

    // 定义正则表达式常量
    private val phoneRegex = Regex("^1[3-9]\\d{9}$")
    private val passwordRegex = Regex("^(?=.{6,20}$)[0-9A-Za-z_\\-@]+$")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        // 使用 DataBinding 设置布局
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
        binding.lifecycleOwner = this

        // 获取 ViewModel 实例
        viewModel = ViewModelProvider(this).get(AuthViewModel::class.java)
        binding.viewModel = viewModel

        // 设置按钮点击、输入监听
        binding.loginButton.setOnClickListener(this)
        binding.registerLink.setOnClickListener(this)
        binding.forgotPasswordLink.setOnClickListener(this)
        binding.phoneInput.addTextChangedListener(this)
        binding.passwordInput.addTextChangedListener(this)
        binding.agreementCheckbox.setOnCheckedChangeListener(this)

        // 观察登录返回结果（此处依旧使用 Toast 显示结果，可根据需求修改为其它展示方式）
        initObserve()
        toastMessage()
    }

    /**
     * 用来初始化观察者，用于处理登录返回结果
     */
    private fun initObserve() {

        viewModel.loginResponse.observe(this) { res ->
            if (res.code == 1) {
                // 登录成功后清空错误提示或显示成功信息
                binding.phoneInput.error = null
                binding.passwordInput.error = null
                res.data?.let { CurrentHolder.setCurrentLoginInfo(it) }
                res.data?.let { CurrentLoginInfo.setCurrentLoginInfo(it) }
                res.data?.let { SharedPrefUtil.saveLoginInfo(this, it) }
                // 如果是激活状态，则跳转到主界面
                if (res.data?.status == 1) {
                    // 登录成功时，保存登录状态到 SharedPreferences
//                        val sharedPref = getSharedPreferences("app_preferences", Context.MODE_PRIVATE)
//                        sharedPref.edit().putBoolean("is_logged_in", true).apply()

                    // 跳转到主页面
                    NavigationUtil.navigateTo(this, SlideNavigationActivity::class.java)
                    finish()

                } else {
                    // 跳转到登录界面
                    ToastUtil.showShort(this, "账号已被封禁，请联系管理员解封")
                }

            } else {
                // 此处你也可以将错误信息展示在界面上的 TextView 中
                ToastUtil.showShort(this, res.msg)
            }
        }
    }

    private fun toastMessage() {
        viewModel.toastMessage.observe(this) { event ->
            event.getContentIfNotHandled()?.let { message ->
                ToastUtil.showShort(this, message)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.login_button -> {
                val phone = binding.phoneInput.text.toString().trim()
                val password = binding.passwordInput.text.toString().trim()
                // 如果输入为空，则直接在输入框显示错误
                if (phone.isEmpty()) {
                    binding.phoneInput.error = "请输入手机号"
                    return
                }
                if (password.isEmpty()) {
                    binding.passwordInput.error = "请输入密码"
                    return
                }
                // 校验手机号格式
                if (!phoneRegex.matches(phone)) {
                    binding.phoneInput.error = "请输入有效的手机号"
                    return
                }
                // 校验密码格式
                if (!passwordRegex.matches(password)) {
                    binding.passwordInput.error =
                        "密码只能由数字、英文字符、下划线、减号和@组成,长度为6-20"
                    return
                }
                // 如果校验通过，清除错误提示
                binding.phoneInput.error = null
                binding.passwordInput.error = null
                // 查看是否同意协议
                if (!binding.agreementCheckbox.isChecked) {
                    binding.agreementCheckbox.error = "请先同意协议"
                    return
                }
                if (binding.agreementCheckbox.error != null) {
                    binding.agreementCheckbox.error = null
                }
                // 调用 ViewModel 的登录方法
                viewModel.login(phone, password)
            }

            R.id.register_link -> {
                // 跳转到注册界面（这里可以自行添加跳转逻辑）
                NavigationUtil.navigateTo(this, AuthActivity::class.java)
            }

            R.id.forgot_password_link -> {
                // 跳转到忘记密码界面（这里可以自行添加跳转逻辑）
                NavigationUtil.navigateTo(this, ForgetPasswordActivity::class.java)
            }
        }
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }


    override fun afterTextChanged(s: Editable?) {
        // 当输入框处于焦点状态时进行实时校验

        // 校验手机号输入框
        if (binding.phoneInput.hasFocus()) {
            val phone = binding.phoneInput.text.toString().trim()
            if (phone.isNotEmpty() && !phoneRegex.matches(phone)) {
                binding.phoneInput.error = "请输入有效的手机号"
            } else {
                binding.phoneInput.error = null
            }
        }
        // 校验密码输入框
        if (binding.passwordInput.hasFocus()) {
            val password = binding.passwordInput.text.toString().trim()
            if (password.isNotEmpty() && !passwordRegex.matches(password)) {
                binding.passwordInput.error =
                    "密码只能由数字、英文字符、下划线、减号和@组成,长度为6-20"
            } else {
                binding.passwordInput.error = null
            }
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        // 处理协议复选框变化，如有需要可在此处添加逻辑
    }
}
